<?php
/**
* 提现记录
*/
class Withdraw extends CS_Controller
{
    private $status = array(1 => '未付', 2 => '已付');

	function _init()
	{
        $this->load->library('pagination');
		$this->load->helper('dictionary');
		$this->load->model('withdraw_model', 'withdraw');
		$this->load->model('withdraw_audit_model', 'withdraw_audit');
		$this->load->model('user_account_model', 'user_account');
		$this->load->model('account_log_model', 'account_log');
	}

	/**
	 * 手动提现列表
	 */
	public function index($pg = 1)
	{
        $getData = $this->input->get();
        $getData['is_from'] = array(1,2);
        $getData = $this->getAuditStatus($getData);
        $page_num = 20;
        $num = ($pg-1)*$page_num;
        $config['first_url']   = base_url('withdraw/index').$this->pageGetParam($this->input->get());
        $config['suffix']      = $this->pageGetParam($this->input->get());
        $config['base_url']    = base_url('withdraw/index');
        $config['total_rows']  = $this->withdraw->total($getData);
        $config['uri_segment'] = 3;
        $this->pagination->initialize($config);
        $data['pg_list']   = $this->pagination->create_links();
        $data['page_list'] = $this->withdraw->page_list($getData, $page_num, $num);
        $data['all_rows']  = $config['total_rows'];
        $data['pg_now']    = $pg;
        $data['status'] = $this->status; //状态
        $this->load->view('withdraw/index', $data);
	}

    /**
     * 获取待审核  已审核 审核失败 sql过滤条件
     */
    private function getAuditStatus($getData)
    {
        if ( ! empty( $getData['auditStatus'] ) ) {
            switch ($getData['auditStatus']) {
                case 1: //待审核
                    $getData['state'] = array(0, 1);
                    break;
                case 2:
                    $getData['state'] = array(2);
                    $getData['audit_status'] = 1;
                    break;
                case 3:
                    $getData['state'] = array(1,2);
                    $getData['audit_status'] = 2;
                    break;
                default:
                    break;
            }
        }
        return $getData;
    }

	/**
	 * 审核
	 */
	public function audit()
	{
		$postData = $this->input->post();

		$withdraw = $this->withdraw->findById($postData['withdraw_id']);
		if ($withdraw->num_rows() == 0)
		{
			$this->error('withdraw/index', '', '提现记录不存在');
		}

        $withdraw = $withdraw->row();

		if ($withdraw->state == 0 && $this->name != 'wfang')//wfang
		{
			$this->error('withdraw/index', '', '你没有权限审核');
		}
		elseif ($withdraw->state == 1 && $this->name != 'hanhong')//hanhong
		{
			$this->error('withdraw/index', '', '你没有权限审核');
		}
		elseif ($withdraw->state == 2)
		{
			$this->success('withdraw/index', '', '已经审核过了');
		}
		$postData['uid']   = $this->uid;
		$postData['name']  = $this->name;

        $transStatus = FALSE;
		if ('2016-10-21 15:14:00' < $withdraw->created_at) { //创建时间大于 上传代码的时间 应该执行之前的方法
            $transStatus = $this->currentWithdrawProcess($withdraw, $postData);
		} else {
			$transStatus = $this->beforeWithdrawProcess($withdraw, $postData);
		}

        if ($transStatus) {
            $this->success('withdraw/index', '', '操作成功');
        } else {
            $this->error('withdraw/index', '', '操作失败');
        }
	}

	/**
	 * 之前提现流程
	 * 1,用户在前台申请提现 将提现的金额 存入到冻结金额字段（amount_settlement）并且余额减掉 提现金额
	 * 2, 后台财务 2审 审核成功以后  将冻结金额减掉提现金额  财务打钱给对方
	 */
	private function beforeWithdrawProcess($withdraw, $postData)
	{
		$this->db->trans_start();
        $account = $this->user_account->findByUid($withdraw->uid)->row();
        if (bccomp($account->amount_settlement, $withdraw->amount) < 0)
        {
            $this->error('withdraw/index', '', '提现出现问题');
        }

        $withdrawData = array('state'=> ($withdraw->state + 1), 'audit_status' => $postData['state']);

        $state = $this->withdraw->updateState($withdraw->withdraw_id, $withdrawData); //修改审核状态
        $audit = $this->withdraw_audit->insertWithdrawAudit($postData); //添加审核记录
        $userAccount['amount_settlement'] = $withdraw->amount;
        if ($postData['state'] == 1) //审核成功
        {
            if ($withdraw->state == 1) //二次审核
            {
                $user = $this->user_account->updateWithdraw($withdraw->uid, $userAccount);   //修改帐号冻结金额
                $log = $this->account_log->insertWithdraw($withdraw, $account->amount_carry);       //添加提现记录
            }
        }
        else  //审核失败
        {
            $userAccount['amount_carry'] = $withdraw->amount;
            $user = $this->user_account->updateWithdraw($withdraw->uid, $userAccount);   //将冻结金额的钱返回给 提现金额
        }
		$this->db->trans_complete();
        return $this->db->trans_status();
	}

	/**
	 * 当前提现流程
	 * 1，用户前台提现申请  在提现表加一条记录
	 * 2, 后台 财务审核  2审 审核成功以后  账户余额减掉提现 金额  财务将钱打给对方
	 */
	private function currentWithdrawProcess($withdraw, $postData)
	{
        $this->db->trans_start();

        $withdrawData = array('state'=> ($withdraw->state + 1), 'audit_status' => $postData['state']);

        $state = $this->withdraw->updateState($withdraw->withdraw_id, $withdrawData); //修改审核状态，原有金额
        $audit = $this->withdraw_audit->insertWithdrawAudit($postData); //添加审核记录
        if ($postData['state'] == 1) {
            if ($withdraw->state == 1) //二次审核
            {
                $amountCarry = bcsub($withdraw->amount_carry, $withdraw->amount, 2);
                $log = $this->account_log->insertWithdraw($withdraw, $amountCarry); //添加提现记录
            }
        } else {  //审核失败
            $userAccount['amount_carry'] = $withdraw->amount;
            $user = $this->user_account->updateWithdraw($withdraw->uid, $userAccount);   //将冻结金额的钱返回给 提现金额
        }

        $this->db->trans_complete();
        return $this->db->trans_status();
	}

	/**
	 * 提现详情
	 */
	public function details($withdrawId)
	{
		$withdraw = $this->withdraw->findById($withdrawId);
		if ($withdraw->num_rows() == 0) {
			$this->error('withdraw/index', '', '提现记录不存在');
		}
		$data['withdrawInfo'] = $withdraw->row();
		$data['withdrawAudit'] = $this->withdraw_audit->findByWithdrawId($withdrawId);
		$this->load->view('withdraw/details', $data);
	}
}